{"componentChunkName":"component---src-templates-post-jsx","path":"/[Algorithm]DynamicProgramming/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"db216133-c9cd-5948-babf-f437eb127d7c","excerpt":"🧷 동적 계획법 (DP) 복잡한 문제를 간단한 여러 개의 문제로 나눠 푸는 방법으로, 큰 의미에서 분할 정복과 같은 접근 방식을 의미한다. 한 가지 문제에 대해, 단 한 번만 풀도록 만들어주는 알고리즘으로, 동일한 연산을 반복하지 않는다. 실행 시간을 줄이기 위해 많이 이용되는 알고리즘 (최적화 알고리즘) 효율성 테스트가 있는 경우, DP나 이진 탐색을 …","html":"<h2>🧷 동적 계획법 (DP)</h2>\n<blockquote>\n<p>복잡한 문제를 간단한 여러 개의 문제로 나눠 푸는 방법으로, 큰 의미에서 분할 정복과 같은 접근 방식을 의미한다.</p>\n</blockquote>\n<p>한 가지 문제에 대해, 단 한 번만 풀도록 만들어주는 알고리즘으로, 동일한 연산을 반복하지 않는다.</p>\n<ul>\n<li>\n<p>실행 시간을 줄이기 위해 많이 이용되는 알고리즘 (최적화 알고리즘)</p>\n<ul>\n<li>\n<blockquote>\n<p>효율성 테스트가 있는 경우, DP나 이진 탐색을 많이 사용한다고들 한다...</p>\n</blockquote>\n</li>\n</ul>\n</li>\n<li>\n<p><strong>Optimal Substructure</strong>에서 효과를 발휘한다.</p>\n<ul>\n<li>\n<blockquote>\n<p>Optimal Substructure: 답을 구하기 위해 이미 했던 동일한 연산을 반복하는 구조로, 최적화 문제의 모든 하위 솔루션은 최적의 솔루션이다. (Principle of Optimality)</p>\n</blockquote>\n</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p><strong>분할 정복과 DP의 차이점?</strong>\n: 문제를 나누는 방식에 있어 차이가 있다. 동적 계획법에서, 어떤 부분 문제는 두 개 이상의 문제를 푸는 데 사용될 수 있어 이 문제의 답을 여러 번 계산하지 않고 한 번만 계산한 후 결과를 재사용하는 방식을 취한다.</p>\n</blockquote>\n<h3>🪚 조건</h3>\n<ul>\n<li>작은 문제에서 반복이 발생</li>\n<li>같은 문제는 항상 같은 정답</li>\n</ul>\n<p>위 두 가지 조건을 충족한다면, 동적 계획법을 사용해 문제를 풀 수 있다. 그리고 한 번 계산한 결과를 저장하기 위해 <strong>Memoization</strong>을 사용한다.</p>\n<blockquote>\n<p><strong>Memoization</strong>\n: 한 번 계산한 문제는 다시 계산하지 않도록 저장해두고 재사용하는 방식</p>\n</blockquote>\n<h3>🪚 예제</h3>\n<p>가장 유명한 예 중 하나는 이항 계수(binomial coefficient)의 계산이다. 이항 계수<span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mo stretchy=\"false\">(</mo><mtable rowspacing=\"0.15999999999999992em\" columnspacing=\"1em\"><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mi>n</mi></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mi>r</mi></mstyle></mtd></mtr></mtable><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">(\\begin{matrix}n\\\\r\\\\ \\end{matrix})</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:2.4000000000000004em;vertical-align:-0.9500000000000004em;\"></span><span class=\"mopen\">(</span><span class=\"mord\"><span class=\"mtable\"><span class=\"col-align-c\"><span class=\"vlist-t vlist-t2\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:1.45em;\"><span style=\"top:-3.61em;\"><span class=\"pstrut\" style=\"height:3em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">n</span></span></span><span style=\"top:-2.4099999999999997em;\"><span class=\"pstrut\" style=\"height:3em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">r</span></span></span></span><span class=\"vlist-s\">​</span></span><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.9500000000000004em;\"><span></span></span></span></span></span></span></span><span class=\"mclose\">)</span></span></span></span>는 n개의 서로 다른 원소 중 r개의 원소를 순서없이 골라내는 방법의 수를 나타낸다.</p>\n<ul>\n<li>그리고 이 점화식을 재귀 호출을 이용하여 구현하면 아래와 같다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">int bino(int n, int r) {\n  if (r == 0 || n == r) return 1;\n  return bino(n - 1, r - 1) + bino(n - 1, r);\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>재귀 호출을 수행하는 과정에서, <strong>동일한 연산이 중복적으로 호출</strong>된다. 그리고 이러한 중복 계산은 n이 증가할 때마다 기하급수적으로 연산량이 증가하도록 만든다.</li>\n<li>\n<p>따라서, 각 n,r 조합에 대해 답을 저장하는 <strong>배열</strong>을 만들어, 각 입력에 대한 반환 값을 저장하도록 변경한다.</p>\n<ul>\n<li>이미 저장된 값이 있다면 이를 재사용하고, 그렇지 않다면 직접 계산한 후 배열에 값을 저장한다.</li>\n<li>즉, <strong>Memoization을 사용해 최적화</strong>를 수행한다.</li>\n</ul>\n</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">// -1로 초기화\nint[][] cache = new int[30][30];\nint bino2(int n, int r) {\n  if (r == 0 || n == r) return 1;\n  if (cache[n][r] != -1) return cache[n][r];\n  return cache[n][r] = bino2(n - 1, r - 1) + bino2(n - 1, r);\n}</code>\n        </deckgo-highlight-code>\n<h3>🪚 구현 방식</h3>\n<p>동적 계획법을 구현하는 방식에 있어 2가지가 가능하다.</p>\n<ul>\n<li>\n<p><strong>Bottom-up</strong>: 작은 문제들부터 해결하면서 전체 답을 구하는 방식</p>\n<ul>\n<li>흔히 반복문을 사용해 구현하고, 재귀 호출을 사용하지 않아 시간과 메모리 사용량을 줄일 수 있다는 장점이 있다.</li>\n</ul>\n</li>\n<li>\n<p><strong>Top-down</strong>: 가장 큰 문제를 방문 후 작은 문제를 호출해 답을 구하는 방식</p>\n<ul>\n<li>흔히 재귀 호출을 사용해 구현하고, 점화식을 직관적으로 이해하기 쉽다는 장점이 있다.</li>\n</ul>\n</li>\n</ul>\n<hr>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://gyoogle.dev/blog\">Tech Interview for developer</a></li>\n<li><a href=\"https://semaph.tistory.com/16\">Top-down(탑다운) vs Bottom-up(바텀업)</a></li>\n<li>[<strong>프로그래밍 대회에서 배우는 알고리즘 문제 해결 전략</strong>] 구종만</li>\n</ul>","frontmatter":{"title":"💡 DP (Dynamic Programming)","date":"May 13, 2022","update":"May 13, 2022","tags":["개발상식","Java","DP"],"series":"💡 Algorithm"},"fields":{"slug":"/[Algorithm]DynamicProgramming/","readingTime":{"minutes":4.725}}},"seriesList":{"edges":[{"node":{"id":"b0e662c4-8dab-58b1-8e34-76fd1f26ad52","fields":{"slug":"/[Algorithm]graph/"},"frontmatter":{"title":"💡 Graph 이론"}}},{"node":{"id":"c1c6944f-734a-5276-8604-a897181207ae","fields":{"slug":"/[Algorithm]문제해결개관/"},"frontmatter":{"title":"💡 문제해결개관"}}},{"node":{"id":"b783c57f-f958-5c14-9935-06b16995e8f1","fields":{"slug":"/[Algorithm]알고리즘분석/"},"frontmatter":{"title":"💡 알고리즘 분석"}}},{"node":{"id":"f3c7f32a-2ead-5bd5-a198-ee5342823217","fields":{"slug":"/[Algorithm]Sorting 알고리즘/"},"frontmatter":{"title":"💡 Sorting 알고리즘"}}},{"node":{"id":"07844ce0-f154-5ad8-b4cc-c6e9bebecc21","fields":{"slug":"/[Algorithm]이분 탐색/"},"frontmatter":{"title":"💡 이분 탐색(Binary Search)"}}},{"node":{"id":"66ab5e60-ccc9-5f85-ad77-8457be4014db","fields":{"slug":"/[Algorithm]HashTable/"},"frontmatter":{"title":"💡 해시 테이블 (Hash Table)"}}},{"node":{"id":"8aa61523-9a0a-5cc7-a670-9750d851b450","fields":{"slug":"/[Algorithm]최장증가수열(LIS)/"},"frontmatter":{"title":"💡 최장 증가 수열(LIS)"}}},{"node":{"id":"db216133-c9cd-5948-babf-f437eb127d7c","fields":{"slug":"/[Algorithm]DynamicProgramming/"},"frontmatter":{"title":"💡 DP (Dynamic Programming)"}}},{"node":{"id":"fa96dd6e-75c9-5a7c-887c-1993125cc7f0","fields":{"slug":"/[Algorithm]최소공통조상(LCA)/"},"frontmatter":{"title":"💡 최소 공통 조상(LCA)"}}},{"node":{"id":"268a7d15-795c-5e9f-9770-eeda9132721d","fields":{"slug":"/[Algorithm]다익스트라알고리즘/"},"frontmatter":{"title":"💡 다익스트라(Dijkstra) 알고리즘"}}},{"node":{"id":"f3a9bade-22f4-54b0-ad9a-b642d6f2b754","fields":{"slug":"/[Algorithm]비트마스크/"},"frontmatter":{"title":"💡 비트마스크(BitMask)"}}}]},"previous":{"fields":{"slug":"/[Programmers]64064/"},"frontmatter":{"title":"👩‍💻 64064. 불량 사용자"}},"next":{"fields":{"slug":"/[Algorithm]최소공통조상(LCA)/"},"frontmatter":{"title":"💡 최소 공통 조상(LCA)"}}},"pageContext":{"id":"db216133-c9cd-5948-babf-f437eb127d7c","series":"💡 Algorithm","previousPostId":"2ace2de6-3978-53ba-97c8-992a0a95ee4a","nextPostId":"fa96dd6e-75c9-5a7c-887c-1993125cc7f0"}},"staticQueryHashes":[]}